package com.liaoyin.travel.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liaoyin.travel.constant.CommonParamter;
import com.liaoyin.travel.entity.Users;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.UsersService;
import io.rong.util.CodeUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;

@Component
public class RongUtils {

    private static final String APPKEY = "RC-App-Key";
    private static final String NONCE = "RC-Nonce";
    private static final String TIMESTAMP = "RC-Timestamp";
    private static final String SIGNATURE = "RC-Signature";


    private static UsersService usersService;

    @Autowired
    public void setUserBasicService(UsersService usersService) {
        RongUtils.usersService = usersService;
    }
    /**
     * 
         * @方法名：getToken
         * @描述： 获取融云tonken
         * @param  type---1:获取tonken,2 刷新用户信息
         * @作者： lijing
         * @日期： 2018年11月9日
     */
    public static String getToken(String id,String type) throws Exception {

        String nonce = String.valueOf(Math.random() * 1000000);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        StringBuilder toSign = new StringBuilder(CommonParamter.RONGYUN_appSecret).append(nonce).append(timestamp);
        String sign = CodeUtil.hexSHA1(toSign.toString());
        Users userInfo = usersService.selectUsersById(id);
        Map<String, String> params=null;
        if (userInfo != null) {
            params = new HashMap<>();
            params.put("portraitUri", StringUtils.isNotBlank(userInfo.getHeadUrl()) ? userInfo.getHeadUrl() : null);
            params.put("name", userInfo.getNickName());
            params.put("userId", id);
            
            Map<String, String> headers = new HashMap<String, String>();
            headers.put(APPKEY, CommonParamter.RONGYUN_appKey);
            headers.put(NONCE, nonce);
            headers.put(TIMESTAMP, timestamp);
            headers.put(SIGNATURE, sign);
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            JSONObject json = null;
            if("1".equals(type)) {
            	json = JSON.parseObject(HttpClientUtils.postForm("http://api.cn.ronghub.com/user/getToken.json", params, headers, null, null));
            	//System.out.println(json.toString()+"aaaaaaaaaaaaaaaaaaaa");
            	if(json != null && json.getInteger("code")== 200) {
                	return json.getString("token");
                }else {
                    System.err.println("没有获取成功");
                	return null;
                }
            }else {
            	json = JSON.parseObject(HttpClientUtils.postForm("http://api.cn.ronghub.com/user/refresh.json", params, headers, null, null));
               // System.out.println(json.toString()+"bbbbbbbbbbbbbbbbbbbbbbb");
            	if(json != null && json.getInteger("code")== 200) {

                	return json.getString("token");
                }else {
                	return "FAIL";
                }
            }
        }else {
        	return null;
        }
    }
    
    
    /**
     * 
     * @方法名：groupManagement
     * @描述： 群组管理
     * @param  type---1:创建群组,2 刷新群组信息
     * @作者： lijing
     * @日期： 2018年11月21日
     * @throws Exception 
     * @throws SocketTimeoutException 
     * @throws ConnectTimeoutException 
     */
    public static String groupManagement (Map<String, String> map,String type) throws Exception {
    	String ret = "";
        if(map == null || map.size() <= 0) {
    	   throw new BusinessException("map.is.null","融云参数错误");
        }
    	String nonce = String.valueOf(Math.random() * 1000000);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        StringBuilder toSign = new StringBuilder(CommonParamter.RONGYUN_appSecret).append(nonce).append(timestamp);
        String sign = CodeUtil.hexSHA1(toSign.toString());
        
        Map<String, String> headers = new HashMap<String, String>();
        headers.put(APPKEY, CommonParamter.RONGYUN_appKey);
        headers.put(NONCE, nonce);
        headers.put(TIMESTAMP, timestamp);
        headers.put(SIGNATURE, sign);
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        JSONObject json = null;
        if("1".equals(type)) {
        	//创建群组
        	json = JSON.parseObject(HttpClientUtils.postForm(CommonParamter.GROUP_CREAT, map, headers, null, null));
        }else if("2".equals(type)) {
        	//刷新群组信息
        	json = JSON.parseObject(HttpClientUtils.postForm(CommonParamter.GROUP_REFRESH, map, headers, null, null));
        }else if("3".equals(type)) {
        	//加入群组
        	json = JSON.parseObject(HttpClientUtils.postForm(CommonParamter.GROUP_JOIN, map, headers, null, null));
        }else if("4".equals(type)) {
        	//退出群组
        	json = JSON.parseObject(HttpClientUtils.postForm(CommonParamter.GROUP_QUIT, map, headers, null, null));
        }else if("5".equals(type)) {
        	//解散群组
        	json = JSON.parseObject(HttpClientUtils.postForm(CommonParamter.GROUP_DISMISS, map, headers, null, null));
        }else if("6".equals(type)) {
        	//发送单聊消息方法
        	json = JSON.parseObject(HttpClientUtils.postForm(CommonParamter.GROUP_PUBLISH, map, headers, null, null));
        }else if("7".equals(type)) {
        	//发送系统消息
        	json = JSON.parseObject(HttpClientUtils.postForm(CommonParamter.GROUP_SYSTEM_PUBLISH, map, headers, null, null));
        }
      //  System.out.println(json.toString()+"aaaaaaaaaaaaaaaaaaaa");
        if(json != null && json.getInteger("code")== 200) {
        	return "SUCCESS";
        }else {
        	return "FAIL";
        }	
    }
    

    public static void main(String[] args) throws Exception{
    	Map<String, String> params = new HashMap<>();
    	 params.put("portraitUri", "1");
         params.put("name", "123");
         params.put("userId", "123");
        //getToken("1cfc80f5dd8311e8b32100163e0cf25f","1",params);
        /*Map<String,Object> contentMap=new HashMap<>();
        contentMap.put("money","悬赏金");
        contentMap.put("beizhu","今日悬赏金已发放");
        contentMap.put("messageType","4");
        contentMap.put("ddid","3025ed9ca48b47fb8622ca78b38d63b2");
    	Map<String, String> map = new HashMap<String,String>();
		map.put("fromUserId","a95b218655ef41389f67b39f9b1fc66f");
		map.put("toUserId", "6ce51c690b794ddd8666bb9ca19428f0&f0f82d0db00c493187fc9362fb0e925f");
		map.put("objectName", "RC:ZzMsg");
		map.put("content", getJsonString(contentMap));
    	groupManagement(map, "6");*/
    }
}